<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryObj.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              class="search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户区域 -->
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="usersList" stripe border>
        <el-table-column type="index" label="编号"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scoped">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scoped.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scoped.row)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scoped.row)"
              ></el-button>

              <!-- 分配角色弹框 -->
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryObj.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户昵称" prop="username">
          <el-input v-model="addForm.username" :disabled="showFlag"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            :type="pwd"
            v-model="addForm.password"
            autocomplete="off"
            :disabled="showFlag"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            :type="pwd"
            v-model="addForm.checkPass"
            autocomplete="off"
            :disabled="showFlag"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleVisible"
      width="50%"
      @close="closeRoleDialog"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleSet">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    //校验确认密码
    var validatePass = (rule, value, callback) => {
      if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    //校验手机号码
    var checkMobile = (rule, value, cb) => {
      const phoneRule = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/

      if (phoneRule.test(value)) {
        //合法手机号码
        return cb()
      }
      cb(new Error('手机号码格式有误！'))
    }
    return {
      //获取用户列表参数的对象
      queryObj: {
        //搜索关键字
        query: '',
        //当前页面值
        pagenum: 1,
        //显示数据的条数
        pagesize: 2
      },
      usersList: [], //用户列表
      total: 0, //总的数据条数
      //控制添加用户对话框的隐藏
      addDialogVisible: false,
      //添加用户表单对象
      addForm: {
        username: '',
        password: '',
        checkPass: '',
        email: '',
        mobile: ''
      },
      //添加用户表单校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度为3~10个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度为6~15个字符',
            trigger: 'blur'
          }
        ],
        checkPass: [
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          },
          { validator: validatePass, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '邮箱地址格式有误', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //添加或修改用户的标题
      title: '添加用户',
      //控制密码输入框是否可编辑
      showFlag: false,
      //存储要修改用户的id
      userId: '',
      //修改密码框的type
      pwd: 'password',
      //控制分配角色弹框
      roleVisible: false,
      //存储要分配角色的用户
      userInfo: {},
      //所有角色列表
      roleList: [],
      //已选择角色的id值
      selectRoleId: ''
    }
  },
  methods: {
    //获取用户列表
    async getUserList() {
      const res = await this.$http.get('users', { params: this.queryObj })
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.usersList = res.data.users
      this.total = res.data.total
      // console.log(this.usersList)
    },

    //监听pagesize改变事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryObj.pagesize = newSize
      this.getUserList()
    },
    //监听 页码值改变事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryObj.pagenum = newPage
      this.getUserList()
    },
    //监听状态开关的改变
    async userStateChange(userinfo) {
      //根据用户传递的过来的id和state发送axios请求
      const res = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        //修改失败的话，不能让其发生变化
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    //关闭并重置添加用户对话框
    closeDialog() {
      //重置表单的预校验信息
      this.$refs.addFormRef.resetFields()
      //人密码框处于可编辑转态
      this.showFlag = false
      //取消对话框的时候把对话框的标题重置为添加用户
      this.title = '添加用户'
      //重置表单
      this.addForm.username = ''
      this.addForm.password = ''
      this.addForm.checkPass = ''
      this.addForm.email = ''
      this.addForm.mobile = ''
    },
    //点击确定添加新用户
    addUser() {
      if (this.showFlag) {
        //showFlag为true就是修改操作
        this.$refs.addFormRef.validate(async valid => {
          if (valid) {
            //预校验通过，发起axios请求修改用户信息
            const res = await this.$http.put(
              `users/${this.userId}`,
              this.addForm
            )
            if (res.meta.status !== 200) return this.$message.error('修改失败')
            //修改成功
            this.$message.success(res.meta.msg)
            //把对话框标题重置为添加用户
            this.title = '添加用户'
            //让密码框可以编辑
            this.showFlag = false
            //隐藏对话框
            this.addDialogVisible = false
            //把密码框的类型改为password
            this.pwd = 'password'
            //重新获取用户列表
            this.getUserList()
            //重置表单
            this.closeDialog()
          }
        })
      } else {
        //showFlag为false为添加用户就是添加操作
        this.$refs.addFormRef.validate(async valid => {
          if (valid) {
            const res = await this.$http.post('users', this.addForm)
            if (res.meta.status !== 201)
              return this.$message.error(res.meta.msg)
            //添加成功
            this.$message.success(res.meta.msg)
            //隐藏添加对话框
            this.addDialogVisible = false
            //重置表单
            this.closeDialog()
            //重新获取用户列表
            this.getUserList()
          }
        })
      }
    },
    //删除用户
    deleteUser(user) {
      //根据当前用户id删除对应的用户
      this.$MessageBox
        .confirm('此操作将永久删除此用户，是否继续？', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const res = await this.$http.delete(`users/${user.id}`)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          //重新获取用户列表
          this.getUserList()
        })
        .catch(() => {
          this.$message.info('取消删除操作')
        })
    },
    //修改用户信息
    async editUser(user) {
      //获取要修改用户的信息
      const res = await this.$http.get(`users/${user.id}`)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败')
      //显示修改用户对话框
      this.addDialogVisible = true
      //把对话框的标题改为修改用户
      this.title = '修改用户'
      //禁用密码输入框
      this.showFlag = true
      //把密码输入框的类型改为text
      this.pwd = 'text'
      //把查询到的用户信息显示到表单中
      this.addForm.username = res.data.username
      this.addForm.email = res.data.email
      this.addForm.mobile = res.data.mobile
      this.addForm.password = '这里不能修改密码哦！'
      this.addForm.checkPass = '这里不能修改密码哦！'
      //把要修改用户的id存储起来
      this.userId = user.id
    },

    //点击分配按钮显示弹框
    async setRole(user) {
      this.userInfo = user
      //展示对话框之前获取所有角色列表
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res)
      //把获取的数据赋给用角色列表
      this.roleList = res.data
      //隐藏弹框
      this.roleVisible = true
    },
    //保存分配角色设置
    async saveRoleSet() {
      if (!this.selectRoleId) {
        console.log(!this.selectRoleId)
        return this.$message.error('请选择要分配的角色')
      }
      // console.log(this.selectRoleId)

      const res = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectRoleId
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.$message.success(res.meta.msg)
      //重新获取列表
      this.getUserList()
      //隐藏弹框
      this.roleVisible = false
    },
    //监听弹框的关闭事件
    closeRoleDialog() {
      this.selectRoleId=''
      this.userInfo={}
    }
  }
}
</script>

<style lang="less" scoped>
.search:hover {
  background-color: #409eff;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
